using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SmartLink.Infrastructure
{
    public static class JsonEx
    {
        /// <summary>
        /// 编译model到josn
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string SerializeObject(this object obj)
        {
            return JsonConvert.SerializeObject(obj);
        }

        /// <summary>
        /// 编译model到josn
        /// </summary>
        /// <param name="obj">自定义的时间数据格式,如果为空,格式为"yyyy'-'MM'-'dd' 'HH':'mm':'ss"</param>
        /// <returns></returns>
        public static string SerializeObject(this object obj, string DateTimeFormat)
        {
            IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
            if (DateTimeFormat != null && DateTimeFormat.Length > 0)
            {
                timeConverter.DateTimeFormat = DateTimeFormat;
            }
            timeConverter.DateTimeFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss";
            return JsonConvert.SerializeObject(obj, Formatting.None, timeConverter);
        }


        /// <summary>
        /// 编译对象到josn
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="NoNullValue">不包含null值</param>
        /// <returns></returns>
        public static string SerializeObject(this object obj, bool NoNullValue)
        {
            if (NoNullValue)
            {
                return JsonConvert.SerializeObject(obj, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore });
            }
            else
            {
                return SerializeObject(obj);
            }
        }

        /// <summary>
        /// 解析json字符串到各种类型
        /// </summary>
        /// <param name="jsonstr"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static object DeserializeObject(this string jsonstr, Type type)
        {
            return JsonConvert.DeserializeObject(jsonstr, type);
        }
        /// <summary>
        ///  解析json字符串到各种类型
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonstr"></param>
        /// <returns></returns>
        public static T DeserializeObject<T>(this string jsonstr)
        {
            if (string.IsNullOrEmpty(jsonstr))
            {
                return default(T);
            }
            return JsonConvert.DeserializeObject<T>(jsonstr);
        }
    }
}
